﻿using System;
using System.Web;
using System.Data;

namespace msBsc.WebUi
{
    public partial class wfPayCashier : msBsc.Cls.BPCustom
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string strTradingNo = "";
                if (!string.IsNullOrEmpty(this.Request.QueryString.Get("NO")))
                {
                    strTradingNo = this.Request.QueryString.Get("NO");
                }
                else if (!string.IsNullOrEmpty(this.Request.QueryString.Get("ID")))
                {
                    strTradingNo = this.Request.QueryString.Get("ID");
                }
                ShowData(strTradingNo);
            }
        }

        //private string strOrderIds="";
        //public DataRow drOrder = null;
        //private string GetOrderCountDesc()
        //{
        //    if (int.Parse(drOrder["ORDRE_COUNT"].ToString()) > 1)
        //    {
        //        return "合并｜" + drOrder["ORDRE_COUNT"].ToString() + "笔订单";
        //    }
        //    else
        //    {
        //        return "单笔订单";
        //    }
        //}
        private void ShowData(string strOrderIds)
        { 
            if (string.IsNullOrEmpty(strOrderIds))
            {
                this.ToErrPage("当前没有找到需要付款的订单，请返回重新选择！");
            }
            using (msBsc.AppLogic.DataAlc.CBizShpOrderForm objgoods = new AppLogic.DataAlc.CBizShpOrderForm())
            {
                strOrderIds = strOrderIds.Replace("'", "");
                DataSet dsList = objgoods.DataObj.QueryBySQL("SELECT  USER_TYPE_CID=MAX(A.USER_TYPE_CID),PAYABLE_AMT=ISNULL(SUM(A.TRADING_AMT),0),ORDRE_COUNT=COUNT(*),TRADING_NO=dbo.strJoin(A.TRADING_NO),TRADING_NME=dbo.strJoin(A.TRADING_NME) FROM SHP_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND A.PAY_DIR='支出' AND A.TRADING_NO IN ('" + strOrderIds.Replace(",", "','") + "') ");
                if (dsList.Tables[0].Rows.Count <= 0)
                {
                    this.ToErrPage("当前没有找到需要付款的订单，可能已经完成付款，请返回重新选择！");
                    return;
                }
                DataRow drOrder = dsList.Tables[0].Rows[0];
                if (int.Parse(drOrder["ORDRE_COUNT"].ToString()) < 1)
                {
                    this.ToErrPage("当前没有找到需要付款的订单，可能已经完成付款，请返回重新选择！");
                    return;
                }

                this.ExecJScript("$('#orderId').val('" + strOrderIds + "');");
                string strtem1="";
                if (int.Parse(drOrder["ORDRE_COUNT"].ToString()) > 1)
                {
                     strtem1= "合并｜" + drOrder["ORDRE_COUNT"].ToString() + "笔订单";
                }
                else
                {
                     strtem1= "单笔订单";
                }
                this.ExecJScript("$('#divOrderCountDesc').html('" + strtem1 + "');");
                this.ExecJScript("$('#spnOnlineAmt').html('" + drOrder["PAYABLE_AMT"].ToString() + "');");
                this.ExecJScript("$('#emPayAMt').html('" + drOrder["PAYABLE_AMT"].ToString() + "');");
                this.ExecJScript("$('#spnOrderNos').html('" + drOrder["TRADING_NO"].ToString() + "');");
                this.ExecJScript("$('#spnOrderNmes').html('" + drOrder["TRADING_NME"].ToString() + "');");

                if (drOrder["USER_TYPE_CID"].ToString() == "1")
                {
                    using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo ouinfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
                    {
                        decimal decUserAmt = ouinfo.GetShopChargeAmt(msBsc.SvRef.UserInfo.Operator);
                        this.ExecJScript("$('#spnUserAmt').html('" + decUserAmt + "');");
                        this.ExecJScript("$('#spnUserType').html('商家帐户');");
                        this.ExecJScript("$('#spnUserNo').html('（帐户号："+msBsc.SvRef.UserInfo.OperDealerId.Split(',')[1]+"）');");
                    }
                }
                else
                {
                    using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ouinfo = new AppLogic.DataAlc.CBizShpCustomerInfo())
                    {
                        decimal decUserAmt = ouinfo.GetUserChargeAmt(msBsc.SvRef.UserInfo.Operator);
                        this.ExecJScript("$('#spnUserAmt').html('" + decUserAmt + "');");
                        this.ExecJScript("$('#spnUserType').html('个人帐户');");
                        this.ExecJScript("$('#spnUserNo').html('（帐户号：" + msBsc.SvRef.UserInfo.Operator + "）');");
                    }
                }


            } 
        }

        private void doConfirmPay()
        {
            using (msBsc.AppLogic.DataAlc.CBizShpChargeTradingLog objtradlog = new AppLogic.DataAlc.CBizShpChargeTradingLog())
            {
                decimal decUserPaidAmt = 0, decOnlinePaidAmt = 0;
                if (decimal.TryParse(this.GetParamHtValue("USER_PAID_AMT"), out decUserPaidAmt))
                {
                    decUserPaidAmt = decimal.Parse(this.GetParamHtValue("USER_PAID_AMT"));
                }
                if (decimal.TryParse(this.GetParamHtValue("ONLINE_PAID_AMT"), out decOnlinePaidAmt))
                {
                    decOnlinePaidAmt = decimal.Parse(this.GetParamHtValue("ONLINE_PAID_AMT"));
                }
                if (decUserPaidAmt < 0M || decOnlinePaidAmt < 0M)
                {
                    this.ToErrPage("数据错误，请返回重新选择！");
                    return;
                }

                DataSet dsList = objtradlog.DataObj.QueryBySQL("SELECT  USER_TYPE_CID=MAX(A.USER_TYPE_CID) FROM SHP_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND A.PAY_DIR='支出' AND A.TRADING_NO IN ('" + this.GetParamHtValue("ID").Replace(",", "','") + "') ");
                if (dsList.Tables[0].Rows.Count <= 0)
                {
                    this.ToErrPage("当前没有找到需要付款的订单，可能已经完成付款，请返回重新选择！");
                    return;
                }
                if (decUserPaidAmt > 0M)
                {
                    DataSet ds1;
                    if (dsList.Tables[0].Rows[0]["USER_TYPE_CID"].ToString() == "1")
                    {
                        ds1 = objtradlog.DataObj.QueryBySQL("SELECT TRADING_PSW FROM SHP_COMMERCIAL_TENANT_INFO A WHERE A.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + "'");
                        if (ds1.Tables[0].Rows.Count <= 0)
                        {
                            Alert("操作不成功：商家账户信息未找到！");
                            return;
                        }
                    }
                    else
                    {
                        ds1 = objtradlog.DataObj.QueryBySQL("SELECT TRADING_PSW FROM SHP_CUSTOMER_INFO A WHERE A.USER_NME='" + msBsc.SvRef.UserInfo.Operator + "'");
                        if (ds1.Tables[0].Rows.Count <= 0)
                        {
                            Alert("操作不成功：个人账户信息未找到！");
                            return;
                        }
                    }
                    if (ds1.Tables[0].Rows[0]["TRADING_PSW"].ToString()!=string.Empty && ds1.Tables[0].Rows[0]["TRADING_PSW"].ToString() != msBsc.AppLogic.Cfg.DesCry.encMe(this.GetParamHtValue("TRADING_PSW"), "zbhtpass"))
                    {
                        Alert("操作不成功：交易密码不正确！");
                        return;
                    }

                }
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        DataRow drLog = objtradlog.PayChargeToMall(this.GetParamHtValue("ID"), decUserPaidAmt, decOnlinePaidAmt);


                        ts.Complete();
                        if (drLog == null)
                        {
                            this.ExecJScript("window.location.href = '/Alipay/return_url.aspx?out_trade_no=" + this.GetParamHtValue("ID") + "';");
                            //this.ExecJScript("layer.msg('已使用账户支付成功付款！',1,{type:1,shade:false});");
                        }
                        else
                        {
                            this.ExecJScript("window.location.href = '/Alipay/default.aspx?ID=" + drLog["CHARGE_TRADING_ID"].ToString() + "';");
                        }
                    }

                //for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                //{
                //    if (ds.Tables[0].Rows[i]["TRADE_STATUS_TXT"].ToString() == "等待买家付款")
                //    {
                //        ds.Tables[0].Rows[i]["TRADE_STATUS_TXT"] = "买家已付款";
                //        ds.Tables[0].Rows[i]["PAID_AMT"] = ds.Tables[0].Rows[i]["PAYABLE_AMT"];
                //        ds.Tables[0].Rows[i]["PAYMENT_DT"] = DateTime.Now;
                //    }
                //}
                //objgoods.Update(ds);
                //using (msBsc.AppLogic.DataAlc.CBizSysUser ouser = new AppLogic.DataAlc.CBizSysUser())
                //{
                //    ouser.UpdateOrderStatistic(msBsc.SvRef.UserInfo.Operator);
                //}
                //if (drLog == null)
                //{
                //    this.ExecJScript("layer.msg('已使用账户支付成功付款！',1,{type:1,shade:false});");
                //}
            }
        }

        public override void DoAction()
        {
            if (this.strAction == "doUpateAmt")
            {
                ShowData(this.GetParamHtValue("ID") );
            }
            else if (this.strAction == "doConfirmPay")
            {
                doConfirmPay();
            }
        }
         
    }
}